#!/usr/bin/env python
# -*- coding: utf-8 -*-

from redmine import Redmine
from urllib import request
from lxml import html
import sys

URL='http://localhost'

def get_issue_id(iid, url=URL, prefix='/issues/'):
    full_url = "%s%s%d.html"%(url, prefix, iid)
    return get_issue_id_by_url(full_url)

def get_issue_id_by_url(full_url):
    doc = html.parse(full_url)
    title = doc.find('.//title').text
    issue_id = title.split(':')[0].split('#')[-1]
    #legacy_id = doc.find('.//a[@id="legacy_issue_id"]').text
    #print(legacy_id, issue_id)
    return issue_id

if __name__ == "__main__":
    redmine = Redmine(URL, username='admin', password='admin')
    project = redmine.project.get('frs')

    tid = 3
    print(tid, get_issue_id(tid))
    sys.exit(0)

    print(dir(project))
    print(dir(project.issues[0]))
    iss = project.issues
    count = 0
    
    for i in iss:
        count = count + 1
        if count>5:
            break

        print(i.id, i.subject)
        if len(i.children):
            print('All children: [')
            for c in i.children:
                print(c.id, end=',')
            print('] End')

        if len(i.custom_fields):
            cf = i.custom_fields
            for v in cf:
                print('---', v, v.value)
        try:
            if i.parent:
                print('###parent', i.parent.id)
        except Exception as e:
            pass
